package io.github.talelin.latticy.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.latticy.bo.BannerWithItems;
import io.github.talelin.latticy.common.configuration.MessageToCodeConfigure;
import io.github.talelin.latticy.common.mybatis.Page;
import io.github.talelin.latticy.dto.banner.BannerDTO;
import io.github.talelin.latticy.mapper.BannerItemMapper;
import io.github.talelin.latticy.mapper.BannerMapper;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.model.BannerItemDO;
import io.github.talelin.latticy.service.BannerService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, BannerDO> implements BannerService {

    @Resource
    private BannerMapper bannerMapper;

    @Resource
    private BannerItemMapper bannerItemMapper;

    @Override
    public BannerDO update(BannerDTO dto, Long id) {
        BannerDO banner = this.getById(id);
        if (banner == null){
            throw new NotFoundException(MessageToCodeConfigure.BANNER_NOT_FOUND);
        }
        BeanUtils.copyProperties(dto,banner);
        this.updateById(banner);
        return null;
    }

    @Override
    public void delete(Long id) {
        BannerDO banner = this.getById(id);
        if (banner == null){
            throw new NotFoundException(MessageToCodeConfigure.BANNER_NOT_FOUND);
        }
        this.removeById(id);
    }

    @Override
    public BannerWithItems getWithItems(Long id) {
        BannerDO banner = this.getById(id);
        if (banner == null){
            throw new NotFoundException(MessageToCodeConfigure.BANNER_NOT_FOUND);
        }

        List<BannerItemDO> bannerItemDOS =
                new LambdaQueryChainWrapper<BannerItemDO>(this.bannerItemMapper)
                .eq(BannerItemDO::getBannerId, id).list();

        return new BannerWithItems(banner,bannerItemDOS);
    }

    @Override
    public IPage<BannerDO> getBannerPage(Page<BannerDO> page) {
        return bannerMapper.selectPage(page,null);
    }
}
